<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/4/11
 * Time: 11:30
 */

class CashMeal_Model extends CI_Model
{

    const CASH_IN_PENDING = 0;
    const CASH_IN_NORMAL = 6;
    const CASH_IN_FAIL = 5;
    const CASH_IN_REMOVE = -1;

    const STATUS_NORMAL = 6;        // 正常
    const STATUS_DISABLE = 5;       // 不可用
    const STATUS_REMOVE = -1;       // 删除

    private $total = 0;
    protected $error = '';

    /**
     * 初始化
     * CashMeal_Model constructor.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @return int
     */
    public function getTotal()
    {
        return $this->total;
    }

    /**
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    public function order($userid, $mealid = 0, $client = '', $source = '')
    {
        $mealDb = clone($this->db);
        $mealDb->where(['id' => $mealid, 'status' => 6]);
        $q = $mealid->get('cash_meal');
        $row = $q->row_array();
        if (empty($row) || empty($row['amount'])) {
            $this->error = '套餐不存在';
            return false;
        }

        $data = [
            'userid' => $userid,
            'sn' => sn(),
            'amount' => $row['amount'],
            'client' => $client,
            'source' => $source,
            'status' => self::CASH_IN_PENDING
        ];

        $orderDb = clone($this->db);
        $orderDb->insert('user_cashin_order', $data);

    }

    /**
     * 获取套餐列表
     * @param int $offset
     * @param int $limit
     * @return null
     */
    public function getMeals($offset = 0, $limit = 100)
    {
        $db = clone($this->db);
        $db->where(['status >' => 0]);
        $this->total = $db->count_all_results('cash_meal');

        $db->order_by('id', 'desc');
        $db->where(['status >' => 0, 'type' => 'system']);
        $query = $db->get('cash_meal');
        $rows = $query->result_array();
        if (empty($rows)) {
            return null;
        }

        foreach ($rows as &$row) {
            $row['amount_format'] = money_format('%i', $row['amount'] / 100);
        }

        return $rows;
    }

    /**
     * Change status
     * @param $params
     * @return mixed
     */
    public function changeStatus($params)
    {
        $id = $params['id'];
        $status = $params['status'];

        $data = [];
        if ($status == 'on') {
            $data['status'] = self::STATUS_NORMAL;
        } else if ($status == 'off') {
            $data['status'] = self::STATUS_DISABLE;
        } else if ($status == 'remove') {
            $data['status'] = self::STATUS_REMOVE;
        }

        $db = clone($this->db);
        $db->where('id', $id);
        $db->update('cash_meal', $data);
        return $db->affected_rows();
    }

    /**
     * Modify meal
     * @param $id
     * @param array $posts
     * @return mixed
     */
    public function modify($id, Array $posts)
    {
        $db = clone($this->db);
        $db->where('id', $id);
        $data = $this->formatParams($posts, 'edit');
        $db->update('cash_meal', $data);
        return $db->affected_rows();
    }

    /**
     * Add meal
     * @param array $posts
     * @return bool
     */
    public function add(Array $posts)
    {
        $data = $this->formatParams($posts, 'add');
        $db = clone($this->db);
        $db->insert('cash_meal', $data);
        if ($id = $db->insert_id()) {
            $q = $db->get_where('cash_meal', ['id' => $id]);
            return $q->row_array();
        }
        return false;
    }

    /**
     * 格式化
     * @param $posts
     * @param string $type
     * @return array
     */
    protected function formatParams($posts, $type = 'add')
    {
        $return = [
            'name' => value($posts, 'name', ''),
            'type' => 'system',
            'amount' => intval($posts['amount']),
            'description' => value($posts, 'description', ''),
            'members' => 0,
            'updatedby' => adminId(),
            'updated' => dateTime()
        ];

        if ($type == 'add') {
            $return['createdby'] = adminId();
            $return['created'] = dateTime();
            $return['status'] = self::STATUS_NORMAL;
        }

        return $return;
    }

    /**
     * 创建自定义套餐
     * @param $userid
     * @param $params
     * @return mixed
     */
    public function createCustomMeal($userid, $params)
    {
        $data = [
            'type' => 'custom',
            'name' => '自定义金额',
            'amount' => $params['amount'],
            'description' => '用户自定义充值金额 ' . money_format('%i', $params['amount'] / 100) . ' 元',
            'members' => 0,
            'created' => dateTime(),
            'createdby' => $userid,
            'updated' => dateTime(),
            'updatedby' => $userid,
            'status' => self::STATUS_NORMAL
        ];

        $db = clone($this->db);
        $db->insert('cash_meal', $data);
        return $db->insert_id();
    }
}

